import { Button, message, Modal, Form } from 'antd';
import React, { useState, useEffect, useRef, useImperativeHandle, forwardRef } from 'react';
import { getLoginUuid, getSqStatus, signCa, getCaOpenStatus } from '@/services/common/api';
import { useModel } from 'umi';
import QRCode from 'qrcode.react';
import { isNull, showMsg } from '@/utils/utils';

interface MyProps {
  _html: Element;
  onClick: Function;
  onLoading: Function;
  loading: Boolean;
  onError: Function;
  module: string;
}

let timerId;
let openStatus = 'N';

const GoodName: React.FC<MyProps> = forwardRef((props, ref) => {

  const { _html, onClick, onLoading, loading, onError, module } = props;

  const [ewm, setEwm] = useState('');

  // const [openStatus, setOpenStatus] = useState('N');

  
  useEffect(() => {
    
  }, []);

  // 暴露的子组件方法，给父组件调用
  useImperativeHandle(ref, () => ({
    onSign: (params, callback) => {
      signForCa(params, callback)
    }
  }))


  // 获取客户生成的唯一id
  const getUuid = async() => {
    await getLoginUuid().then(res => {
      onLoading(false);
      if (res.code === '0') {
        setEwm(`claim?identifyPrepareLoginUuid=${res.identifyPrepareLoginUuid}&identifyUuid=${Math.round(Math.random()*10000000)}`)
      } else {
        showMsg(res?.message);
      }
    }).catch(error => {
      onLoading(false);
      showMsg(error?.data?.message)
    });
  }
  // 非文案签署接口
  const signForCa = async(params, callback) => {
    onLoading(true);
    console.log('openStatus', openStatus);
    if (openStatus === 'Y') {
      await signCa(params).then(res => {
        onLoading(false);
        if (res.code === '0') {
          callback?.();
        } else {
          onError?.();
          showMsg(res?.message);
        }
      }).catch(error => {
        onLoading(false);
        onError?.();
        showMsg(error?.data?.message)
      });
    } else {
      callback?.();
      onLoading(false);
    }
    
  }

  // 10s轮询一次支付结果
  const timer = () => {
    timerId = setInterval(()=> getShouqStatus('refresh'), 5000);
  }

  // 获取授权状态
  const getShouqStatus = async(flag?: string) => {
    onLoading(true);
    await getSqStatus().then(res => {
      // 已授权
      if (res.status === 'Y') {
        clearInterval(timerId);
        timerId = null;
        setEwm('');
        onClick();
        onLoading(false);
      } else {
        clearInterval(timerId)
        timerId = null;
        timer();
        if (isNull(flag)) {
          getUuid();
        } else {
          onLoading(false);
        }
        
      }
    }).catch(error => {
      onLoading(false);
      showMsg(error?.data?.message)
    });
  }

  const getOpenStatus = async() => {
    onLoading(true);
    await getCaOpenStatus(module).then(res => {
      // setOpenStatus(res.is_open);
      // res.is_open = 'N'
      openStatus = res.is_open;
      if (res.is_open === 'Y') {
        getShouqStatus();
      } else {
        onLoading(false);
        onClick();
      }
    }).catch((error) => {
      onLoading(false);
      console.log('error', error);
      showMsg(error?.data?.message || error?.errmsg)
    });
  }
  
  console.log('renderopenstatus', openStatus)

  return (
    <div>
      <div onClick={() => getOpenStatus()}>{_html}</div>
      {
        !isNull(ewm) &&
        <Modal
          title="请扫描二维码进行授权"
          wrapClassName="order-modal"
          width="30%"
          maskClosable={false}
          visible
          confirmLoading={loading}
          onOk={() => { clearInterval(timerId); timerId = null; getShouqStatus('refresh')}}
          onCancel={() => { setEwm(''); clearInterval(timerId); timerId = null; }}
          okText='刷新'
        >
          <div style={{ textAlign: 'center' }}>
            <QRCode
              // value参数为生成二维码的链接
              value={ewm}
              // 二维码的宽高尺寸
              size={150}
              // 二维码的颜色
              fgColor="#000"
              renderAs="svg"
            />
          </div>
        </Modal>
      }
    </div>
  );
});

export default GoodName;
